package com.itheima.webserver.service;

import com.itheima.dubbo.interfaces.ManageApi;
import org.bson.types.ObjectId;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.model.domain.Admin;
import com.itheima.commons.model.mongo.Message;
import com.itheima.commons.model.mongo.Publish;
import com.itheima.commons.model.vo.ErrorResult;
import com.itheima.dubbo.interfaces.PublishApi;
import com.itheima.dubbo.interfaces.SystemUserApi;
import com.itheima.webserver.exception.MyException;
import com.itheima.webserver.interceptor.AdminThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: alongchan
 * @Date: 2021/12/16 20:22
 * @Description:
 */
@Service
public class SystemService {
    @Reference
    private SystemUserApi systemUserApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Reference
    private PublishApi publishApi;

    //获取登录验证码
    public void getVerification(String uuid, HttpServletResponse response) {
        //HuTool工具获取验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String code = lineCaptcha.getCode();

        //将uuid和验证码存入到redis中,用于后期校验
        redisTemplate.opsForValue().set(Constants.ADMIN_LOGIN_CODE, code);
        redisTemplate.opsForValue().set(Constants.ADMIN_LOGIN_UUID, uuid);

        //设置响应类型，将验证码写入到响应中
        response.setContentType("image/jpg");
        try {
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new MyException(ErrorResult.verificationCodeInitError());
        }
    }

    //管理员登录
    public String adminLogin(Map<String, String> params) {


        String uuid = params.get("uuid");
        String username = params.get("username");
        String password = params.get("password");
        String verificationCode = params.get("verificationCode");
        //1.校验username,password,code是否有空值
        if (!StrUtil.isAllNotBlank(username, password, verificationCode)) {
            throw new MyException(ErrorResult.adminLoginInfoHasEmptyMsg());
        }
        //2.校验验证码和uuid
        String code = redisTemplate.opsForValue().get(Constants.ADMIN_LOGIN_CODE);
        String UUID = redisTemplate.opsForValue().get(Constants.ADMIN_LOGIN_UUID);
        if (!code.equals(verificationCode) || !UUID.equals(uuid)) {
            throw new MyException(ErrorResult.verificationCodeCheckError());
        }
        //3.校验管理员信息
        Admin admin = systemUserApi.findAdmin(username, password);
        if (ObjectUtil.isEmpty(admin)) {
            throw new MyException(ErrorResult.loginInfoError());
        }

        //4.生成token返回
        Map<String, Object> map = new HashMap<>();
        map.put("AdminId", admin.getUid());
        map.put(JWTPayload.EXPIRES_AT, DateTime.of(System.currentTimeMillis() + Constants.JWT_TIME_OUT));
        String token = JWTUtil.createToken(map, Constants.JWT_SECRET.getBytes());
        return token;

    }

    //获得管理员信息
    public Admin getAdminProfile(Long userId) {
        return systemUserApi.findAdminByAdminId(userId);
    }

    //管理员退出登录
    public void adminLoginOut() {
        //删除线程中的token信息
        AdminThreadLocal.remove();
    }
}
